from flask import Flask,jsonify,render_template,request,escape
from api import geocode,around,weatherInfo
from panduan import panduan_login
from vsearch import search4letters
from pymysql import connect
import pandas as pd
import os
import direction

app = Flask(__name__)
os.getcwd()

names = []
address2 = []


# 调用日志记录函数
def log_request(req:'flask_request',res:str)->None:
	with open('vsearch.log','a') as log:
		print(req.form,req.remote_addr,req.user_agent,res,file=log,sep='|')

def log_address(req:'name',res:'address')->None:
	with open('address.log','a') as log:
		print(req,res,file=log,sep='|')

def look_over():
	con = connect(host="127.0.0.1",port=3306,user="root",password="123456",db="user")
	cursor1 = con.cursor()
	sql = "select * from student"
	cursor1.execute(sql)
	res = cursor1.fetchall()
	print(res)
	return res


# 登录页
@app.route('/login')
def login_page() -> 'html':
	return render_template('login.html',the_title ="欢迎使用大学速查宝！")


# 登录功能
@app.route('/addlogin',methods=['POST'])
def addlogin() -> 'html':
	zhanghao = request.form.get("zhanghao") 
	mima = request.form.get("mima")
	a = panduan_login(zhanghao, mima)
	log_request(request,a)
	if a == "true":
		return render_template('cod1.html',the_title ="")
	else:
		return "登录失败"

# 添加账号
@app.route('/addstudentpage',methods=["GET"])
def addstudent_page() -> "html":
	return render_template("addstudentpage.html")


# 添加功能
@app.route('/addstudent',methods=["POST"])
def addstudent():
	con = connect(host="127.0.0.1",port=3306,user="root",password="123456",db="user")
	cursor5 = con.cursor()
	student_id = request.form.get("student_id")
	student_name = request.form.get("student_name")
	student_code = request.form.get("student_code")
	sql = "insert into useradmin set id='%s', name='%s',password='%s'"% (student_id, student_name,student_code)
	cursor5.execute(sql)
	con.commit()
	return render_template("addsucesspage.html")


#路径规划功能

@app.route('/base')
def base():
    title = '输入起止点，帮助规划步行'
    return render_template('cod1.html',
                          
                            he_title=title,)

#路径页面
@app.route('/search', methods=['POST'])
def do_search1() -> 'html':
    key = "12f80238641864b66003f76e69819ee4"
    start_address = request.form['start_address']
    end_address = request.form['end_address']
    title = '建议如下'
    df = direction.direction_walking(key, start_address, end_address)
    results = df.loc[:, ['instruction', 'distance', 'duration']]
    results.columns = ['指引', '路程', '时间']
    total_walk = direction.total_walk(df)
    total_walk_time = direction.total_walk_time(df)
    route = results['指引'].tolist()
    log_request(request, route)
    return render_template('results1.html',
                           the_title=title,
                           the_start_address=start_address,
                           the_end_address=end_address,
                           the_results=results,
                           the_html_table=results.to_html(index=False),
                           the_total_walk=total_walk,
                           the_total_walk_time=total_walk_time,)

#字典提取功能，拿来查询大学资料
dict_school_data= dict()
file_names = [x for x in os.listdir('data')]
for f in file_names:
    with open('data/{fn}'.format(fn = f),'r') as file_object:
        dict_school_data[f.strip('.txt')] = file_object.read().splitlines()

@app.route('/search4', methods=['POST'])
def do_search() -> 'html':
    name = request.form['name']
    return render_template('results.html',
                           the_name = name,
                           the_data = dict_school_data['{sn}'.format(sn = name)],
                           )

# 查询页面
@app.route('/')
@app.route('/entry')
def entry_page() -> 'html':
    return render_template('entry.html',
                           the_title='广州本科大学资料查询')



@app.route('/1')
def entry_page2() ->'html':
	return render_template('cod1.html',the_title='直接可用')

# 页面功能返回图
@app.route('/ob',methods=['POST'])
def go_search():
	address = request.form['address']
	codes = str(geocode(address)['geocodes'][0][ 'location'])

	location = codes
	types = request.form['types']
	results = around(location,types)['pois']
	for i in results:
		names.append(i['name'])
		address2.append(i['address'])
	return render_template('biaodan2.html',res=names,the_title='为您返回的结果：',the_data=address2)


# 详情页面
@app.route('/details',methods=['POST'])
def xiangqing():
	youge = request.form["youge"]
	combine = dict(zip(names,address2))
	sql = "%s"%youge
	thedata = combine[sql]
	return render_template('biaodan3.html',res=combine,the_title='详情页：',the_data=thedata)


# 查看日志
@app.route('/viewlog',)
def view_the_log() ->'html':
	with open('vsearch.log','r') as log:
		contents = []
		for line in log:
			contents.append([])
			for item in line.split('|'):
				contents[-1].append(escape(item))

	titles = ('Form Data','Remote_addr','User_agent','Results')
	return render_template('viewlog.html',
			the_title= "欢迎进入日志浏览界面！",
			the_row_titles= titles,
			the_data=contents,)

if __name__ == '__main__':
	app.run(debug=True)